namespace Simnova.Collaborate.WinForm
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using Simnova.Collaborate.Presenter;
    using Simnova.Collaborate.View;
    using System.Runtime.InteropServices;

    public partial class TimeLog : Form, ITimeLog
    {
        private InterceptKeys _interceptKeys;
        private TimeLogPresenter _timeLogPresenter;
        private DateTime _startTime;
        private int _userId;


        public TimeLog(int userId)
        {
            this._userId = userId;
            this.InitializeComponent();
        }

        #region FlashWindowStuff

        public enum FLASHWINFOFLAGS
        {
            FLASHW_STOP = 0,
            FLASHW_CAPTION = 0x00000001,
            FLASHW_TRAY = 0x00000002,
            FLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY),
            FLASHW_TIMER = 0x00000004,
            FLASHW_TIMERNOFG = 0x0000000C
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct FLASHWINFO
        {
            public uint cbSize;
            public IntPtr hwnd;
            public int dwFlags;
            public uint uCount;
            public int dwTimeout;
        }

        [DllImport("user32.dll")]
        public static extern int FlashWindowEx(ref FLASHWINFO pfwi);



        #endregion



        public void ShowWindow()
        {
            Show();
            WindowState = FormWindowState.Normal;
            Activate();
        }

        private void TimeLog_Load(object sender, EventArgs e)
        {
            this._timeLogPresenter = new TimeLogPresenter(this, this._userId);
            this._interceptKeys = new InterceptKeys();
            this._interceptKeys.StartWatching();
            this._interceptKeys.OnComboPressedEvent = new InterceptKeys.KeyComboPressedHandler(this.ShowWindow);

            this.durationTextBox.Text = "0";
            this.timeTimer.Start();
            this.durationTextBox.Text = DateTime.Now.Subtract(_startTime).TotalMinutes.ToString();
        }

        private void addEntryButton_Click(object sender, EventArgs e)
        {
            this._timeLogPresenter.SaveTimeLogEntry();
            this.durationTextBox.Text = DateTime.Now.Subtract(this._startTime).TotalMinutes.ToString();
            this.descriptionTextBox.Text = "";
            this._timeLogPresenter.GetCurrentTimeLogEntry();
            this.timeTimer.Start();                        
        }

        private void addAndCloseButton_Click(object sender, EventArgs e)
        {
            this._timeLogPresenter.SaveTimeLogEntry();
            Application.Exit();
        }

        private void resetTimerButton_Click(object sender, EventArgs e)
        {
            this._timeLogPresenter.DeleteTimeLogEntry();
            this._timeLogPresenter.GetCurrentTimeLogEntry();
            this.durationTextBox.Text = "0";
            this.timeTimer.Start();
        }

        private void adminButton_Click(object sender, EventArgs e)
        {
            Admin adminWin = new Admin(this._userId);
            adminWin.ShowDialog(this);
        }

        private void companyComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this._timeLogPresenter == null) return;
            this._timeLogPresenter.LoadRoles();
        }

        private void roleComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this._timeLogPresenter == null) return;
            this._timeLogPresenter.LoadActivityTypes();
        }

        private void TimeLog_FormClosed(object sender, FormClosedEventArgs e)
        {
            this._interceptKeys.StopWatching();
            Application.Exit();
        }

        private void reminderCheckbox_CheckedChanged(object sender, EventArgs e)
        {
            if (!this.reminderCheckbox.Checked)
            {
                this.reminderTimer.Stop();
            }
            else
            {
                this.reminderTimer.Start();
            }
        }

        private void timeTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan elapsedTime = DateTime.Now.Subtract(this._startTime);
            this.durationTextBox.Text = Convert.ToInt16(elapsedTime.TotalMinutes).ToString();
        }

        private void reminderTimer_Tick(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.notifyIcon1.ShowBalloonTip(10000, "Time Logging Reminder", "Reminder to Log Time", ToolTipIcon.Info);
            }
            else
            {
                // Flash the window
                FLASHWINFO fwi = new FLASHWINFO();
                fwi.cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(FLASHWINFO)));
                fwi.hwnd = this.Handle;
                fwi.dwFlags = (int)
                              (FLASHWINFOFLAGS.FLASHW_ALL | FLASHWINFOFLAGS.FLASHW_TIMERNOFG);
                fwi.dwTimeout = 0;
                FlashWindowEx(ref fwi);
            }
        }

     





        #region ITimeLog Members

        string ITimeLog.Description
        {
            get { return this.descriptionTextBox.Text; }
            set { this.descriptionTextBox.Text = value; }
        }

        DateTime ITimeLog.StartTime
        {
            set {
                this._startTime = value; 
            }
        }

        int ITimeLog.Duration
        {
            get { return int.Parse(this.durationTextBox.Text); }
        }

        System.Collections.IList ITimeLog.LogEntries
        {
            set { this.dataGridView1.DataSource = value; }
        }

        System.Collections.IList ITimeLog.Companies
        {
            set 
            {
                this.companyComboBox.DataSource = value;
                this.companyComboBox.DisplayMember = "Name";
                this.companyComboBox.ValueMember = "CompanyId";
            }
        }

        int ITimeLog.SelectedCompanyId
        {
            get 
            {
                if (this.companyComboBox.SelectedValue == null) return 0;
                int companyId;
                int.TryParse(this.companyComboBox.SelectedValue.ToString(), out companyId);
                return companyId;
            }
        }

        System.Collections.IList ITimeLog.Roles
        {
            set
            {
                this.roleComboBox.DataSource = value;
                this.roleComboBox.DisplayMember = "Name";
                this.roleComboBox.ValueMember = "RoleId";
            }
        }

        int ITimeLog.SelectedRoleId
        {
            get
            {
                if (this.roleComboBox.SelectedValue == null) return 0;
                int roleId;
                int.TryParse(this.roleComboBox.SelectedValue.ToString(), out roleId);
                return roleId;
            }
        }

        System.Collections.IList ITimeLog.ActivityTypes
        {
            set
            {
                this.activityTypeComboBox.DataSource = value;
                this.activityTypeComboBox.DisplayMember = "Name";
                this.activityTypeComboBox.ValueMember = "ActivityTypeId";
            }
        }

        int ITimeLog.SelectedActivityTypeId
        {
            get
            {
                if (this.activityTypeComboBox.SelectedValue == null) return 0;
                int activityTypeId;
                int.TryParse(this.activityTypeComboBox.SelectedValue.ToString(), out activityTypeId);
                return activityTypeId;
            }
        }

        System.Collections.IList ITimeLog.Tasks
        {
            set
            {
                this.taskComboBox.DataSource = value;
                this.taskComboBox.DisplayMember = "Name";
                this.taskComboBox.ValueMember = "TaskId";
            }
        }

        int ITimeLog.SelectedTaskId
        {
            get
            {
                if (this.taskComboBox.SelectedValue == null) return 0;
                int taskId;
                int.TryParse(this.taskComboBox.SelectedValue.ToString(), out taskId);
                return taskId;
            }
        }

        int ITimeLog.RemainingHours
        {
            get
            {
                int remainingHours = 0;
                int.TryParse(this.remainingHoursTextBox.Text, out remainingHours);
                return remainingHours;
            }
        }

        #endregion

 

        private void TimeLog_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
            {
                Hide();
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
        }



        private void TimeLog_FormClosing(object sender, FormClosingEventArgs e)
        {
            /*
            if (DialogResult.Yes == MessageBox.Show(

                  this,

                  "Do you want to save the current entry?",

                  "Save Last Entry?",

                  MessageBoxButtons.YesNo))
            {

                _timeLogPresenter.SaveTimeLogEntry();

            } else
            {
                e.Cancel = true;

            }
            */
        }

        private void viewReportsButton_Click(object sender, EventArgs e)
        {
            ReportViewer rv = new ReportViewer(this._userId);
            rv.ShowDialog(this);
        }
    }
}
